const db = require('../db/index')
module.exports = {
  getArtCates: (req, res) => {
    db.query('select * from ev_artical_cate where is_delete=0 order by id asc', (err, result) => {
      if (err) return res.cc(err)
      res.send({
        status: 0,
        message: '获取文章分类列表成功',
        data: result
      })
    })
  },
  addArtCates: (req, res) => {
    // SQL查重
    db.query('select * from ev_artical_cate where name=? or alias=?', [req.body.name, req.body.alias], (err, result) => {
      console.log(result);
      if (err) return res.cc(err)

      if (result.length === 2) return res.cc('分类名称与别名已经被占用，请更换后重试')

      if (result.length === 1 && result[0].name === req.body.name && result[0].alias === req.body.alias) return res.cc('分类名称与分类别名已经被占用，请更换后重试')
      if (result.length === 1 && result[0].name === req.body.name) return res.cc('分类名称被占用，请更换后重试')
      if (result.length === 1 && result[0].alias === req.body.alias) return res.cc('分类别名被占用，请更换后重试')
      // ------------名称与别名都可用 便添加-----------
      db.query('insert into ev_artical_cate set ?', req.body, (err, result) => {
        if (err) return res.cc(err)
        if (result.affectedRows !== 1) return res.cc('新增文章分类失败')
        res.cc('新增文章分类成功', 0)
      })

    })
  },
  deleteCateById: (req, res) => {
    db.query('update ev_artical_cate set is_delete=1 where id =?', req.params.id, (err, result) => {
      if (err) return res.cc(err)
      if (result.affectedRows !== 1) return res.cc('删除文章分类失败')
      res.cc('删除文章分类成功', 0)
    })
  },
  addCateById: (req, res) => {
    db.query('select * from ev_artical_cate where id =?', req.params.id, (err, result) => {
      if (err) return res.cc(err)
      if (result.length !== 1) return res.cc('获取文章分类数据失败')
      res.send({
        status: 0,
        message: '获取文章分类数据成功',
        data: result[0]
      })
    })
  },
  updateCateById: (req, res) => {
    // 查重
    db.query('select * from ev_artical_cate where id<>? and (name=? or alias=?)', [req.body.id, req.body.name, req.body.alias], (err, result) => {
      if (err) return res.cc(err)
      if (result.length === 2) return res.cc('分类名称与别名被占用，请更换后重试')
      if (result.length === 1 && result[0].name === req.body.name && result[0].alias === req.body.alias) return res.cc('分类名称与别名被占用，请更换后重试')
      if (result.length === 1 && result[0].name === req.body.name) return res.cc('分类名称被占用，请更换后重试')
      if (result.length === 1 && result[0].alias === req.body.alias) return res.cc('分类别名被占用，请更换后重试')
      // 查重完毕 更新数据
      db.query('update ev_artical_cate set ? where id=?', [req.body, req.body.id], (err, result) => {
        if (err) return res.cc(err)
        if (result.affectedRows !== 1) return res.cc('更新文章分类失败')
        res.cc('更新文章分类成功',0)
      })
    })

  }
}